﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LDSP.Helper;
using BYFW.DAL;
using System.Data;
using LDSP.BRL;
using LDSP.Util;

namespace LDSP.UI.EnterpriseAdmin.ItemDefinition
{
    public partial class MngChemical : LDSP.BRL.BaseEnterprisePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.RB())
                {
                    this.InitDataDynamicBefore();
                    if (!IsPostBack)
                    {
                        this.InitData();
                        //this.BindGrid();
                    }
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        public override void RedirectBefore()
        {
            if (LoginUser == null)
            {
                this.GoToLogin();
            }
        }

        private int col_chk = 0;
        private int col_index = 1;
        private int col_catalog = 2;
        private int col_name = 3;
        private int col_cas = 4;
        private int col_un = 5;

        /// <summary>
        /// 传入参数，设置过滤条件
        /// </summary>
        protected void SetSpecialPageInfo()
        {
            g_pageInfo.Direction = true;
            g_pageInfo.Sort = "name";
            g_pageInfo.PageSize = GetPageSizeSetting();
            g_pageInfo.PageIndex = this.grd_list.PageIndex;
        }
        protected bool RB()
        {
            //企业管理员和用户都可以查
            return true;// this.AllowEnterpriseUser();
        }
        protected void InitData()
        {
            this.SetSpecialPageInfo();
            BindDDLPageSize();
            //不缓存则清空页面信息
            if (!needCachePageInfo)
            {
                g_pageInfo.ClearPageInfo();
            }
            this.BindDDLFields();
        }
        protected void BindDDLPageSize()
        {
            CommonControlInitial.InitialPageSize(this.ddl_pageSize);
            this.ddl_pageSize.SelectedValue = g_pageInfo.PageSize.ToString();
        }
        protected void InitDataDynamicBefore()
        {
        }
        protected void BindGrid()
        {
            DataTable dt = new DataTable();
            //如果没有输入搜索条件的话，则不显示结果
            if (this.txt_value.Text.Trim() != "")
            {
                this.grd_list.Visible = true;
                dt = BYFW.SFL.CommonOP.SortedTable(new Chemical().GetRecords(g_pageInfo.ConditionWhere, true), g_pageInfo.GetSortExpression());
                this.grd_list.PageSize = g_pageInfo.PageSize;
                this.grd_list.PageIndex = g_pageInfo.PageIndex;
                this.grd_list.DataSource = dt;
                this.grd_list.DataBind();

                SavePageSizeSetting();
            }
            else
            {
                this.grd_list.Visible = false;
            }

            this.TotalRecords.Text = LDSP.Helper.StringUtil.GetSearchText(dt.Rows.Count);

            this.ShowResult(dt.Rows.Count > 0);
        }

        protected void BindDDLFields()
        {
            this.ddl_fields.Items.Clear();
            this.ddl_fields.Items.Add("中文化学名/别名");
            this.ddl_fields.Items.Add("美国化学文摘号(CAS)");
            this.ddl_fields.Items.Add("联合国危险货物编号(UN)");
            this.ddl_fields.Items.Add("海关商品编号");

            try
            {
                this.ddl_fields.SelectedIndex = 0;
            }
            catch { }

        }
        protected void GetCondition()
        {
            string cond = "";
            if (this.ddl_fields.SelectedIndex == 0)
            {
                cond = this.AppendConditionMulti(cond, this.txt_value.Text.Trim(), "name", "alias");
            }
            if (this.ddl_fields.SelectedIndex == 1)
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("CAS", EDataType.String, "%" + this.txt_value.Text + "%", "like", true), true);
            }
            if (this.ddl_fields.SelectedIndex == 2)
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("UN", EDataType.String, "%" + this.txt_value.Text + "%", "like", true), true);
            }
            if (this.ddl_fields.SelectedIndex == 3)
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("GoodsNumber", EDataType.String, "%" + this.txt_value.Text + "%", "like", true), true);
            }

            g_pageInfo.Condition = cond;
        }

        private void ShowResult(bool hasResult)
        {
            lbl_result.Text = string.Format("您查询的{0}：【{1}】" + (hasResult ? "已经收录在以下名录中：" : "没有在任何名录中找到。"),
                this.ddl_fields.SelectedItem.Text,
                this.txt_value.Text);
        }

        protected void btn_search_Click(object sender, EventArgs e)
        {
            try
            {
                this.GetCondition();
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_export_Click(object sender, EventArgs e)
        {
            ChemicalExport export = new ChemicalExport();

            //获取选中行的数据。
            List<int> ids = new List<int>();
            for (int i = 0; i < this.grd_list.Rows.Count; i++)
            {
                CheckBox chb = (CheckBox)this.grd_list.Rows[i].FindControl("chb");
                if (chb.Checked)
                {
                    ids.Add(this.GetInt(this.grd_list.DataKeys[i].Value));
                }
            }

            //获取化学品列表。
            IList<Chemical> chemicals = new List<Chemical>();
            foreach (int id in ids)
            {
                Chemical chemical = new Chemical();
                chemical.GetProperties(id);
                chemicals.Add(chemical);
            }

            //导出数据
            export.Export(Server, chemicals);
        }

        protected void grd_list_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    var ett = UIHelper.GetEntityFromGridViewRow<Chemical>(e.Row);
                    this.ShowSequenceNumber(e.Row, col_index);

                    //显示化学品名录。
                    string catalog = string.Empty;
                    try
                    {//尝试将化学品名录的id转换成名称。
                        DataRow c_catalog = new ChemicalCatalog().GetRecordByID(Int32.Parse(ett.Catalog));
                        if (c_catalog != null)
                        {
                            catalog = c_catalog["name"].ToString();
                        }
                    }
                    catch { }
                    e.Row.Cells[col_catalog].Text = catalog;

                    e.Row.ToolTip = StringUtil.ConstructChemicalTitle(ett);
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                g_pageInfo.PageIndex = e.NewPageIndex;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                if (g_pageInfo.Sort == e.SortExpression)
                {
                    g_pageInfo.Direction = !g_pageInfo.Direction;
                }
                else
                {
                    g_pageInfo.Direction = true;
                }
                g_pageInfo.Sort = e.SortExpression;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void ddl_pageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                g_pageInfo.PageSize = this.GetInt(this.ddl_pageSize.SelectedValue);
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
    }

}